define(function(require, exports, module) {

  var Backbone = require('backbone');
  var $ = require('jquery');
  var _ = require('lodash');
  var jsonview = require('jsonview');
  var moment = require('moment')

  // var echarts = require('js/echarts');
  var echarts = require('/npm/show-react16-r15.20-uyuncomponents/node_modules/echarts/dist/echarts')
  
  var env = window.env;

  // var line = require('v/graph/option/line-time-static')
  // var line = require('v/graph/option/line-confidenceband')
  // var line = require('v/graph/data/line-time')
  // var line_time = require('v/graph/option/line-time-2')
  var line_time = require('v/graph/option/line-time-3')
  var line_1 = require('v/graph/option/line-abnormity')
  var line = require('v/graph/option/line')

  // var lineTime = _.map(line.series[0].data, function(item) {
  //   return item.value[0]
  // })

  // _.each(lineTime, function(item) {
  //   console.log(moment(item).format(), item)
  // })

  var tmpl = require('text!../tmpl/t.html')


  function measureCanvasText(text, fontSize, fontFamily) {
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d');
    fontSize = fontSize || 12;
    fontFamily = fontFamily || 'sans-serif';
    ctx.font = `${fontSize}px ${fontFamily}`;
    return ctx.measureText(text);
  }

  function main() {
    $('#main').append(tmpl)

    var $app = $('#line').width(env.w).height(env.h).addClass('bg');

    var chart = echarts.init($app[0]);
    chart.setOption(line)

    var $chart2 = $('#line_1').width(1200).height(env.h).addClass('bg');

    var chart_line_1 = echarts.init($chart2[0]);

    var $line_time = $('#line_time').width(1200).height(env.h).addClass('bg');

    var chart_time = echarts.init($line_time[0]);

    // line_1.dataZoom = null
    line_1.visualMap = null
    line_1.series[2].lineStyle.color = '#43a1fb'

    var series = line_1.series
    var startTime = series[2].data[0][0];
    var endTime = series[2].data[series[2].data.length - 1][0];
    
    var noOutRange = true
    var colorStops = []
    var outOfRangeIndexes = []
    _.each(series[2].data, (item, index) => {
      var l = series[0].data[index][1]
      var u = series[1].data[index][1] + l
      var v = item[1];
      var time = item[0];
      var offset = (time - startTime) / (endTime - startTime)
      if (v != null && (v <= l || v >= u)) {
        colorStops.push({
          offset: offset,
          color: '#ff0000'
        })
        noOutRange = false;
        outOfRangeIndexes.push(index);
      } else {
        colorStops.push({
          offset: offset,
          color: '#43a1fb'
        })
      }
    })

    var method = '3'
    switch (method) {
      case '1':
        break
      
      case '2':
        if (!noOutRange) {
          var lastColor = ''
          var newColorStops = []
          _.each(colorStops, (colorStop, index) => {
            if (colorStop.color !== lastColor) {
              if (index - 1 > 0 && newColorStops[newColorStops.length - 1] !== colorStops[index - 1]) {
                newColorStops.push(colorStops[index - 1]);
              }
              newColorStops.push(colorStop)
              lastColor = colorStop.color
            }
          })
          if (newColorStops[newColorStops.length - 1] !== colorStops[colorStops.length - 1]) {
            newColorStops.push(colorStops[colorStops.length - 1])
          }
    
          line_1.series[2].lineStyle.color = {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: newColorStops,
            global: false
          }
        }
        break;
        
      case '3':
        if (!noOutRange) {
          series[3] = _.cloneDeep(series[2])
          series[3].lineStyle.color = '#ff0000';
          
          _.each(series[3].data, item => {
            item[1] = null
          })
          var extendRangeIndexes = []

          var dataLen = series[2].data.length

          _.each(outOfRangeIndexes, index => {
            if (index - 1 > 0) {
              extendRangeIndexes.push(index - 1)
            }
            extendRangeIndexes.push(index)
            if (index + 1 < dataLen) {
              extendRangeIndexes.push(index + 1);
            }
          })
          var uniqRangeIndexes = _.uniq(extendRangeIndexes)
          _.each(uniqRangeIndexes, index => {
            series[3].data[index][1] = series[2].data[index][1];
          })
        }
        
        break;
    }

    chart_line_1.setOption(line_1)
    // 
    // 

    // data: [[],[]] 或 data: [{value:[]},{value:[]}]
    line_time.series[0].data.sort((a, b) => {
      return (a.value ? a.value[0] : a[0]) - (b.value ? b.value[0] : b[0])
    })

    if (1) {
      var datas = line_time.series[0].data;
      var len = datas.length;
      var min = datas[0].value ? datas[0].value[0] : datas[0][0];
      var max = datas[len-1].value ? datas[len-1].value[0] : datas[len-1][0]
      // line_time.xAxis.min = min
      // line_time.xAxis.max = max

      var duration = max - min;
      line_time.xAxis.splitNumber = 0
      // delete line_time.xAxis.splitNumber
      // line_time.xAxis.interval = (max - min) / 8
      // line_time.xAxis.axisLabel.showMinLabel = true
      // line_time.xAxis.axisLabel.showMaxLabel = true
      const TimeFormat = 'H:mm:ss'

      var textSize = measureCanvasText(moment(min).format(TimeFormat))
      var maxCount = Math.floor(1180 / textSize.width)

      var interval = Math.ceil(duration / (maxCount-2))

      // var s = Math.round(interval / 1000)
      // if (s > 0) {
      //   var m = Math.round(s / 60)
      //   if (m > 0) {
      //     var h = Math.round(m / 60)
      //     if (h > 0) {
      //       interval = h * 60 * 60 * 1000
      //     } else {
      //       interval = m * 60 * 1000
      //     }
      //   } else {
      //     interval = s * 1000
      //   }
      // }

      line_time.xAxis.interval = interval

      // line_time.xAxis.axisLabel.formatter = function (value) {
      //   return moment(value).format(TimeFormat);
      // }
      // line_time.tooltip.formatter = function (params) {
      //   let html = moment(params[0].axisValue).format(TimeFormat)
      //   _.each(params, item => {
      //     html += '<br/>' + item.marker + item.seriesName + ': ' + item.value[1]
      //   })
      //   return html
      // }
    }
    
    
    chart_time.setOption(line_time)

    $('#test').click(function() {
      // chart.clear()
      // chart.dispatchAction({
      //   type: 'legendToggleSelect',
      // // 切换的图例名称
      // name: 'A'
      // // 所有图例的选中状态表
      // // selected: Object
      // })
    })

    // step(chart)

  }

  function dataProcess(arr) {
    return arr.map(function(item) {
      item += 0.01;
      return item;
    })
  }

  function step(chart) {

    var draw = function() {
      // requestAnimationFrame(draw);

      var data = line.series[0].data;
      line.series[0].data = dataProcess(data);

      chart.setOption(line, true)
    }

    draw();
    
  }

  return main;
})
